package com.holyland.action;

import static com.holyland.util.IHolylandConstants.SESSION_USER;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.interceptor.validation.SkipValidation;

import com.holyland.model.User;
import com.holyland.service.MemberService;
import com.holyland.util.HolylandException;

public class LoginAction extends BaseAction {
	
	private static final long serialVersionUID = -6578109560891575201L;
	private String username;
	private String password;		
	
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}	
	
	@SkipValidation
	public String showLogin() {
		String errMsg = request.getParameter("errMsg");				
		
		if(StringUtils.isNotBlank(errMsg)) {
			addActionError(errMsg);
		}		
		
		return FWD_SUCCESS;
	}				
	
	public String login() throws HolylandException { 
		String adminName = "Administrator";
		String adminUserName = "admin";
		String adminPswd = "admin123";									
			
		User user = null;
		
		if(!StringUtils.equals(adminUserName, username)) {					
			user = MemberService.getInstance().findUserByUserName(username);
			
			if(user != null) {
				
				String pswd = user.getPassword();
				
				if(StringUtils.equals(pswd, password)) {
					boolean firstTime = user.isFirstTimeLogin();
					
					session.put(SESSION_USER, user);
					
					if(firstTime) {										
						return "changePswd";
					}
				} else {
					addActionError("Pengguna atau Kata Kunci salah.");				
					return FWD_INPUT;
				}				
			} else {
				addActionError("Pengguna atau Kata Kunci salah.");				
				return FWD_INPUT;
			}
		} else {
			if(!StringUtils.equals(adminPswd, password)) {
				addActionError("Pengguna atau Kata Kunci salah.");						
				
				return FWD_INPUT;
			}	
			
			user = new User();
			user.setUsername(adminUserName);
			user.setName(adminName);
			user.setAdmin(true);
			
			session.put(SESSION_USER, user);
		}																
		
		return FWD_SUCCESS;
	}
	
	@SkipValidation
	public String doLogout() {
		session.clear();
		
		return FWD_SUCCESS;
	}

	@Override
	public void validate() {
		if(StringUtils.isBlank(username)) {
			addActionError("Pengguna (harus diisi)");
		}
		
		if(StringUtils.isBlank(password)) {
			addActionError("Kata Kunci (harus diisi)");
		}
	}		
}
